#include "lcd.h"

void initLCD(void) {
	IODIR1 |= (LCD_DATA | LCD_E | LCD_RS);
	IOCLR1 = (LCD_DATA | LCD_E | LCD_RS);

	IODIR0 |= LCD_RW;
	IOCLR0 = LCD_RW;

	IODIR0 |= LCD_BACKLIGHT;
	IOCLR0 = LCD_BACKLIGHT;
}

void delay37us(void) {
	volatile tU32 i;

	//Temp test for 140 uS delay
	for (i = 0; i < 6 * 2500; i++)
		asm volatile (" nop");
	//delay 15 ns x 2500 = about 37 us delay
}

void writeLCD(tU8 reg, tU8 data) {
	volatile tU8 i;

	if (reg == 0)
		IOCLR1 = LCD_RS;
	else {
		IOSET1 = LCD_RS;
	}

	IOCLR0 = LCD_RW;
	IOCLR1 = LCD_DATA;
	IOSET1 = ((tU32) data << 16) & LCD_DATA;
	IOSET1 = LCD_E;
	for (i = 0; i < 16; i++)
		asm volatile (" nop");
	//delay 15 ns x 16 = about 250 ns delay
	IOCLR1 = LCD_E;
	for (i = 0; i < 16; i++)
		asm volatile (" nop");
	//delay 15 ns x 16 = about 250 ns delay
}

void lcdBacklight(tU8 onOff) {
	if (onOff == TRUE)
		IOSET0 = LCD_BACKLIGHT;
	else {
		IOCLR0 = LCD_BACKLIGHT;
	}
}

void writeString(char * s, int N) {
	int i;
	for (i = 0; i < N; i++) {
		writeLCD(1, s[i]);
		delay37us();
	}
}

void resetCursor() {
	writeLCD(0, 0x02);
	osSleep(1);
}

void lcdInit(void) {
	initLCD();

	//display off
	writeLCD(0, 0x8); //
	delay37us();

	//display clear
	writeLCD(0, 0x01);
	osSleep(1); //actually only 1.52 mS needed

	//function set
	writeLCD(0, 0x38);
	delay37us();

	//display control set
	writeLCD(0, 0x0c);
	delay37us();

	lcdBacklight(TRUE);
}

void printCelsius() {
	writeLCD(1, 223);
	delay37us();
	writeLCD(1, 'C');
	delay37us();
}

void printPadding(int N) {
	while(N--) {
		writeLCD(1, ' ');
		delay37us();
	}
}

int print(int * figure) {
	int ret = 1;
	if (*figure < 0)
	{
		writeString("-", 1);
		*figure = -*figure;
		ret++;
	}
	int digit = *figure % 10;
	*figure = *figure / 10;
	if (*figure > 0 || *figure % 10 != 0)
		ret += print(figure);


	writeLCD(1, digit+'0');
	delay37us();
	return ret;
}

int printInt(int figure) {
	int tmp = figure;
	return print(&tmp);
}
